package com.qf.cloud2204.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TestZuulFilter2 extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;  // 前置过滤器
    }

    @Override
    public int filterOrder() {
        return 4;  // 过滤器的序号，越小的先执行
    }

    @Override
    public boolean shouldFilter() {

        RequestContext currentContext = RequestContext.getCurrentContext();
        // 获取之前的过滤器设置的 sendZuulResponse属性，如果之前过滤器已经
        // 不想发送该请求了，那么这个过滤器也不进入run方法
        boolean b = currentContext.sendZuulResponse();
        return b;
    }

    @Override
    public Object run() throws ZuulException {

//        System.out.println("!!!!!!!!!!!!!!!!!!!!");
        // 校验token 的合法性
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getHeader("token");

        if (!token.equals("123456")){ // 模拟校验
            currentContext.setSendZuulResponse(false);
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.getWriter().println("token error");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
